package br.ufmg.bandex;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Verify if the app is being created now or is being restarted
        if(savedInstanceState == null) {
            //Only connect and get the site data if the app is starting now
            this.fetchWebsite(BandexConnection.RU_SETORIAL_II);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_ru_1:
                this.fetchWebsite(BandexConnection.RU_SETORIAL_I);
                return true;
            case R.id.action_ru_2:
                this.fetchWebsite(BandexConnection.RU_SETORIAL_II);
                return true;
            case R.id.action_ru_saude_direito:
                this.fetchWebsite(BandexConnection.RU_SAUDE_DIREITO);
                return true;
            case R.id.action_ru_ica:
                this.fetchWebsite(BandexConnection.RU_ICA);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void fetchWebsite(int restaurantID) {
        TextView tv = (TextView) findViewById(R.id.appText);
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInf = connMgr.getActiveNetworkInfo();

        //Verify the device connectivity
        if (netInf != null && netInf.isConnected()) {
            Log.d("Bandex", "Connected to the internet.");
            tv.setText(getString(R.string.message_connecting));
            new BandexConnection().execute(restaurantID);
        } else {
            Log.e("Bandex", "Could not connect to the internet.");
            tv.setText(getString(R.string.message_no_connection));
        }
    }

    private class BandexConnection extends AsyncTask<Integer, Void, String> {

        private static final int RU_SETORIAL_I = 6;
        private static final int RU_SETORIAL_II = 1;
        private static final int RU_SAUDE_DIREITO = 2;
        private static final int RU_ICA = 5;

        private URL url;
        private HttpURLConnection httpConn;

        @Override
        protected String doInBackground(Integer... params) {
            String urlParameters = "__EVENTTARGET=ctl00%24contentPlaceHolder%24drpRestaurante&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=%2FwEPDwULLTE3NTgxMDg3NzYPZBYCZg9kFgICAw9kFggCBw8WAh4EVGV4dAXOCzx1bD48bGk%2BPGEgY2xhc3M9J2JvcmRlckJvdHRvbTInIGhyZWY9J2h0dHA6Ly93d3cuZnVtcC51Zm1nLmJyL2NvbnRldWRvLmFzcHg%2FcGFnaW5hPTEzMyc%2BIGNvbW8gdGVyIGFjZXNzbyBhb3MgYmVuZWbDrWNpb3MgZGEgZnVtcDwvYT48L2xpPjxsaT48YSBjbGFzcz0nYm9yZGVyQm90dG9tMicgaHJlZj0naHR0cDovL3d3dy5mdW1wLnVmbWcuYnIvY29udGV1ZG8uYXNweD9wYWdpbmE9MjU3Jz4gbWlzc8Ojbywgdmlzw6NvIGUgdmFsb3JlczwvYT48L2xpPjxsaT48YSBjbGFzcz0nYm9yZGVyQm90dG9tMicgaHJlZj0naHR0cDovL3d3dy5mdW1wLnVmbWcuYnIvY29udGV1ZG8uYXNweD9wYWdpbmE9NSc%2BIGhpc3TDs3JpYSBkYSBmdW1wPC9hPjwvbGk%2BPGxpPjxhIGNsYXNzPSdib3JkZXJCb3R0b20yJyBocmVmPSdodHRwOi8vd3d3LmZ1bXAudWZtZy5ici9jb250ZXVkby5hc3B4P3BhZ2luYT0yJz4gY29udHJpYnVpw6fDo28gcGFyYSBhIGFzc2lzdMOqbmNpYSBlc3R1ZGFudGlsPC9hPjwvbGk%2BPGxpPjxhIGNsYXNzPSd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NQPAtrvkNQPAtrvrLsHAtrvrLsHAtrvuJ4OAtrvuJ4OAtrv1OUBAtrv1OUBAtrv4MgIAtrv4MgIAtrv%2FC8C2u%2F8LwLa78jEBgLa78jEBgLa7%2BSrDgLa7%2BSrDgL1hajsBAL1hajsBAL1hcSzDAL1hcSzDAL1hdCWBwL1hdCWBwL1hez9DgL1hez9DgL1hfjAAQL1hfjAAQL1hZSkCQL1hZSkCQL1haALAvWFoAsC9YW87gsC9YW87gsC9YWIhw4C9YWIhw4C9YWk6gEC9YWk6gEC0KyKwwIC0KyKwwIC0KympgoC0KympgoC0KyyjQ0C0KyyjQ0C0KzO0AQC0KzO0AQC0KzatwwC0KzatwwC0Kz2mgcC0Kz2mgcC0KyC%2Fg4C0KyC%2Fg4C0KyexQEC0KyexQHd%2B41aHt2uaT51MQbqwNqIt5y2Vg%3D%3D&ctl00%24txtBusca=Buscar&ctl00%24contentPlaceHolder%24drpRestaurante=" + params[0];
            try {
                //Create the connection
                this.url = new URL(getString(R.string.bandex_url));
                this.httpConn = (HttpURLConnection) url.openConnection();
                this.httpConn.setReadTimeout(10000);
                this.httpConn.setConnectTimeout(15000);
                this.httpConn.setRequestMethod("POST");
                this.httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                this.httpConn.setDoInput(true);
                this.httpConn.setDoOutput(true);

                //Send request
                Log.d("Bandex", "Creating data outputstream...");
                DataOutputStream dataOS = new DataOutputStream(this.httpConn.getOutputStream());
                Log.d("Bandex", "Data outputstream created.");
                dataOS.writeBytes(urlParameters);
                dataOS.flush();
                dataOS.close();
                Log.d("Bandex", "Data outputstream send.");
                this.httpConn.connect();

                //Verify the connection
                if(this.httpConn.getResponseCode() != 200) {
                    Log.e("Bandex", httpConn.getResponseMessage());
                    return null;
                }

                //Read the response
                return this.getSiteContent(this.httpConn);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Log.e("Bandex", "Error malformedURLException.");
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("Bandex", "IOException creating website connection.");
            }
            return null;
        }

        @Override
        protected void onPostExecute(String siteContent) {
            TextView tv = (TextView)findViewById(R.id.appText);

            if(siteContent == null) {
                tv.setText(getString(R.string.message_connection_failed));
                Log.e("Bandex", "onPostExecute received null as parameter.");
            }
            else {
                tv.setText(siteContent);
                Log.d("Bandex", "onPostExecute wrote its text on screen.");
            }

            //Release resources
            this.httpConn.disconnect();
        }

        private String getSiteContent(HttpURLConnection conn) {
            String siteLine;
            BufferedReader buffReader;
            InputStreamReader inStreamReader;

            try {
                //Get the connection
                Log.d("Bandex", "Creating website input stream.");
                inStreamReader = new InputStreamReader(conn.getInputStream());
                buffReader = new BufferedReader(inStreamReader);
                Log.d("Bandex", "Input stream created");
                //Begin reading the stream
                Log.d("Bandex", "Start reading input stream.");
                siteLine = buffReader.readLine();
                while(siteLine != null) {
                    if(siteLine.contains("Almoço")) {
                        //Close the streams and return the formated string
                        buffReader.close();
                        inStreamReader.close();
                        return formatHtmlText(siteLine);
                    }
                    siteLine = buffReader.readLine();
                }
                //Close the streams before leaving
                buffReader.close();
                inStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("Bandex", "IOException reading input stream.");
            }

            //If the string could not be found, return null
            return null;
        }

        private String formatHtmlText(String text) {
            String formatedString = "";
            int copyStart = 0;
            boolean tagEnded = false;

            int textLength = text.length();

            for(int i = 0; i < textLength; i++) {
                if(tagEnded) {
                    if(text.charAt(i) == '<') {
                        if(copyStart != i) {
                            formatedString = formatedString.concat(text.substring(copyStart, i) + "\n");
                            Log.i("Bandex", "String concat: " + text.substring(copyStart, i));
                        }
                        tagEnded = false;
                    }
                }
                else {
                    if(text.charAt(i) == '>') {
                        tagEnded = true;
                        copyStart = i + 1;
                    }
                }
            }

            return formatedString;
        }
    }
}
